package com.stuManager.servlet;

import com.alibaba.fastjson.JSON;
import com.stuManager.dao.UserDao;
import com.stuManager.model.CommonResponseModel;
import com.stuManager.model.User;
import com.stuManager.service.LoginService;
import com.stuManager.util.CookiesUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
/*
    LogoutServlet
    登出接口，将会把登录生成的token从cookie和服务端数据库中移除
 */
@WebServlet(name = "LogoutServlet", value = "/logout")
public class LogoutServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 获取一个service
        LoginService service = new LoginService();
        //2 准备要返回的数据
        CommonResponseModel m = new CommonResponseModel();
        //3 获取请求中的token
        Cookie token = CookiesUtil.getCookieByName(request, "token");
        if (token == null) {
            m.setErrorCode(1);
            m.setMessage("token为null");
        }
        else {
            //4 登出的操作
            m = service.logoutService(token.getValue());
            if (m.getErrorCode() == 0) {
                // 5 登出若成功，通知浏览器移除token
                CookiesUtil.setCookie(response,"token", null, 0);
            }
        }
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        String jsonString = JSON.toJSONString(m);
        response.getWriter().print(jsonString);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
